package lk.exception;

import lk.util.HttpServletUtil;
import lk.util.SessionUtil;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 后台登录拦截器
 *
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    private int flag = 1;

    private List<String> list = new ArrayList(Arrays.asList(new String[]{"/file/upload", "/file/download", "/login","/register"}));

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = SessionUtil.getRequest().getRequestURI();
        for (String s : list) {
            if (url.endsWith(s)) {
                return true;
            }
        }
        if (flag == 1 && request.getSession().getAttribute("user") == null) {
            HttpServletUtil.writeObjectJSON2Response(response,new RestfulRecord(403,"未登录，不能访问"));
            return false;
//            throw new InvalidTokenException("用户拦截");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
